package com.zuoban.log;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.extra.servlet.ServletUtil;
import com.zuoban.entity.sys.SysLog;
import com.zuoban.mapper.SysLogMapper;
import com.zuoban.util.CurrentUser;
import com.zuoban.util.HttpUtil;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.util.Optional;

/**
 * @BelongsProject: zuoban-boot
 * @BelongsPackage: com.zuoban.log
 * @Author: zxy
 * @CreateTime: 2022-10-10
 * @Description: ...
 */
@Component(value = "logObserver")
public class LogObserverImpl implements Observer {

    @Resource
    private Snowflake snowflake;

    @Resource
    private SysLogMapper sysLogMapper;

    @Override
    public void addLog(HttpServletRequest request, SysLog sysLog) {
        sysLog.setId(new BigInteger(String.valueOf(snowflake.nextId())));
        sysLog.setUserId(sysLog.getUserId() == null ? CurrentUser.getUserId() : sysLog.getUserId());
        sysLog.setIp(ServletUtil.getClientIP(request));
        try {
            sysLog.setAddress(HttpUtil.httpGet("https://ip.taobao.com/service/getIpInfo.php?ip="+ServletUtil.getClientIP(request)));
        } catch (Exception exception) {
            sysLog.setAddress("当前归属地");
        }
        sysLogMapper.insert(sysLog);
    }
}
